import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:star_author/config/app.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/handler/common_permission_handler.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/route/route_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:star_author/widgets/tap_transition_widget.dart';
import 'package:provider/provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

class Alert {
  static Future showLoginTip(String msg, BuildContext context,
      {bool clearToken = false}) {
    return showCustomDialog(
        Container(
            width: double.infinity,
            child: Text(msg,
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontWeight: FontWeight.normal,
                    decoration: TextDecoration.none,
                    fontSize: 16.sp,
                    color: ColorConf.normal))),
        context as BuildContext,
        cancelText: '稍后登录',
        confirmText: '去登录', onConfirm: () {
      if (clearToken) {
        var userModal = Provider.of<UserProvider>(context, listen: false);
        userModal.clearToken();
      }
      App.preRouteName = Get.currentRoute; //登陆前存放路由 用于跳转到我的页面
      RouteUtil.onVerifyLogin();
    });
  }

  static Future showCustomDialog(Widget body, BuildContext context,
      {String confirmText = '确认提交',
      Function? onConfirm,
      String cancelText = '取消'}) {
    if (onConfirm == null) onConfirm = () {};

    return showDialog<String>(
      context: context,
      barrierDismissible: true, // user must tap button!
      builder: (BuildContext context) => AlertDialog(
        insetPadding: EdgeInsets.symmetric(vertical: 0),
        contentPadding: EdgeInsets.only(top: 20.0.w, bottom: 0.w),
        content: Container(
          child: Flex(
            mainAxisSize: MainAxisSize.min,
            direction: Axis.vertical,
            children: [
              Container(
                  width: 300.w,
                  padding: EdgeInsets.symmetric(horizontal: 12.0.w),
                  child: body),
              Container(
                margin: EdgeInsets.only(top: 24.0.w),
                decoration: BoxDecoration(
                    border:
                        Border(top: BorderSide(color: ColorConf.darkWhite))),
                height: 43.w,
                padding: EdgeInsets.only(bottom: 0),
                child: Flex(
                  direction: Axis.horizontal,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      flex: 1,
                      child: OutlinedButton(
                        style: OutlinedButton.styleFrom(
                          primary: ColorConf.yellow,
                          fixedSize: Size.fromHeight(43.w),
                          side: BorderSide(style: BorderStyle.none),
                          shape: const RoundedRectangleBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(0))),
                        ),
                        onPressed: () {
                          Navigator.pop(context, 'Cancel');
                        },
                        child: Text(cancelText,
                            style: TextStyle(
                              color: ColorConf.lightGray,
                              fontSize: 16.sp,
                              decoration: TextDecoration.none,
                              fontWeight: FontWeight.w400,
                            )),
                      ),
                    ),
                    Container(
                      width: 1.w,
                      height: 43.w,
                      color: ColorConf.darkWhite,
                    ),
                    Expanded(
                      flex: 1,
                      child: OutlinedButton(
                        style: OutlinedButton.styleFrom(
                          primary: ColorConf.yellow,
                          fixedSize: Size.fromHeight(43.w),
                          side: BorderSide(style: BorderStyle.none),
                          shape: const RoundedRectangleBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(0))),
                        ),
                        onPressed: () {
                          Navigator.of(context).pop();
                          onConfirm?.call();
                        },
                        child: Text(confirmText,
                            style: TextStyle(
                              color: ColorConf.yellow,
                              fontSize: 16.sp,
                              decoration: TextDecoration.none,
                              fontWeight: FontWeight.w400,
                            )),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  static showToast(
    BuildContext context, {
    required dynamic content,
    String? title,
    bool custom = false,
    String cancelText = '',
    String confirmText = '',
    dynamic Function()? onCancel,
    dynamic Function()? onConfirm,
    int? delay: null,
  }) {
    Widget getText(String value) {
      return Text(
        value,
        style: TextStyle(
          fontSize: 16.sp,
          color: ColorConf.normal,
        ),
        textAlign: TextAlign.center,
      );
    }

    Widget render() {
      List<Widget> list = [];
      if (content is Widget) return content;
      if (title != null) {
        list.add(
          Container(
            margin: EdgeInsets.only(bottom: 10.w),
            child: Center(
              child: Text(
                title,
                style: TextStyle(
                  color: ColorConf.normal,
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        );
      }
      if (content is String) {
        list.add(getText(content));
      }
      if (content is List) {
        content.forEach((text) {
          list.add(getText(text));
        });
      }
      return Column(
        children: list,
      );
    }

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext _content) {
        return StatefulBuilder(
          builder: (BuildContext __context, StateSetter setState) {
            List<Widget> buttonList = [
              if (checkNotNullOrNotEmpty(cancelText))
                _CountDownButton(
                  text: cancelText,
                  color: ColorConf.lightGray,
                  onPressed: onCancel ??
                      () {
                        BuildContext context = App.materialKey.currentContext!;
                        Navigator.of(context).pop('dialog');
                      },
                  border: true,
                ),
              if (checkNotNullOrNotEmpty(confirmText))
                _CountDownButton(
                  text: confirmText,
                  color: ColorConf.yellow,
                  delay: delay,
                  onPressed: onConfirm ?? () {},
                )
            ];
            return AlertDialog(
              backgroundColor: ColorConf.transparent,
              elevation: 0,
              contentPadding: EdgeInsets.all(0),
              content: custom
                  ? content as Widget
                  : Container(
                      decoration: BoxDecoration(
                        color: ColorConf.white,
                        borderRadius: GetRadius.all(8.w),
                      ),
                      width: Get.width * 0.8,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Container(
                            padding: EdgeInsets.symmetric(
                                vertical: 24.w, horizontal: 15.w),
                            child: render(),
                          ),
                          if (checkNotNullOrNotEmpty(cancelText) ||
                              checkNotNullOrNotEmpty(confirmText))
                            Container(
                              decoration: BoxDecoration(
                                  border: Border(
                                      top: BorderSide(
                                          width: 1, color: Color(0xFFEEEEEE)))),
                              child: Row(
                                children: buttonList,
                              ),
                            )
                        ],
                      ),
                    ),
            );
          },
        );
      },
    );
  }

  static showActionSheet(
    BuildContext context, {
    required Widget content,
    Function()? onClosed,
  }) {
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return Container(
          decoration: BoxDecoration(
            color: ColorConf.white,
            borderRadius: GetRadius.only(topLeft: 12.w, topRight: 12.w),
          ),
          padding: EdgeInsets.only(top: 12.w),
          child: content,
        );
      },
    ).whenComplete(() => onClosed?.call());
  }

  static Future error(String message, BuildContext context) {
    return showDialog<String>(
      context: context,
      builder: (BuildContext context) => AlertDialog(
        content: Text(message),
        actions: <Widget>[
          TextButton(
            onPressed: () => Navigator.pop(context, 'OK'),
            child: Text(
              'OK',
              style: TextStyle(color: ColorConf.orange, fontSize: 16.sp),
            ),
          ),
        ],
      ),
    );
  }

  static Future<void> showPickerDialog(
    BuildContext context, {
    Function(List<File>)? fromGalleryCallback,
    required Function(File? file) fromCameraCallback,
    int maxCount: 1,
    multiImagesInGallery = false,
    RequestType requestType: RequestType.image,
    bool enableRecording: false,
  }) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          contentPadding: EdgeInsets.all(20),
          title: Text('图片选择',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: ColorConf.normal,
                height: 1.42,
                fontSize: 20.sp,
                decoration: TextDecoration.none,
                fontWeight: FontWeight.w500,
              )),
          content: SingleChildScrollView(
            child: Container(
              width: double.infinity,
              child: Column(
                children: [
                  Container(
                    width: double.infinity,
                    child: OutlinedButton(
                      child: Text('从相册中选择',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: ColorConf.yellow,
                            fontSize: 18.sp,
                            decoration: TextDecoration.none,
                            fontWeight: FontWeight.normal,
                          )),
                      style: OutlinedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 8.0.w),
                        primary: ColorConf.yellow,
                        side: BorderSide(color: ColorConf.yellow, width: 1),
                      ),
                      onPressed: () {
                        Function _callBack = () async {
                          Navigator.pop(context);
                          //仿微信图片选择assets = {_GrowableList} size = 1
                          final List<AssetEntity>? assets =
                              await AssetPicker.pickAssets(context,
                                  maxAssets: maxCount,
                                  requestType: requestType);
                          if (assets == null) return;
                          List<File> files = [];
                          if (requestType == RequestType.video) {
                            EasyLoading.show(status: "上传中...");
                          }
                          for (AssetEntity entity in assets) {
                            File? file = await entity.file;
                            files.add(file!);
                          }
                          fromGalleryCallback!(files);
                        };

                        CommonPermissionHandler.iosPhotosRequestPermission(
                            context, () {
                          _callBack();
                        });
                      },
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10.w),
                    width: double.infinity,
                    child: OutlinedButton(
                      child: Text('拍照',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: ColorConf.yellow,
                            fontSize: 18.sp,
                            decoration: TextDecoration.none,
                            fontWeight: FontWeight.normal,
                          )),
                      style: OutlinedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 8.0.w),
                        primary: ColorConf.yellow,
                        side: BorderSide(color: ColorConf.yellow, width: 1),
                      ),
                      onPressed: () {
                        Function _callBack = () async {
                          Navigator.pop(context);
                          final AssetEntity? entity =
                              await CameraPicker.pickFromCamera(
                            context,
                            enableRecording: enableRecording,
                            onlyEnableRecording:
                                requestType == RequestType.video,
                          );
                          if (entity != null) {
                            if (requestType == RequestType.video) {
                              EasyLoading.show(status: "上传中...");
                            }
                            File? file = await entity.file;
                            fromCameraCallback(file);
                          } else {
                            return;
                          }
                          // File? image = await picker.pickImage(
                          //     source: ImageSource.camera);
                          //
                          // if (image == null) return;
                          // fromCameraCallback(image);
                        };

                        CommonPermissionHandler.cameraRequestPermission(context,
                            () {
                          _callBack();
                        });
                      },
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10.w),
                    width: double.infinity,
                    child: OutlinedButton(
                      child: Text('取消',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: ColorConf.yellow,
                            fontSize: 18.sp,
                            decoration: TextDecoration.none,
                            fontWeight: FontWeight.normal,
                          )),
                      style: OutlinedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 8.0.w),
                        primary: ColorConf.yellow,
                        side: BorderSide(color: ColorConf.yellow, width: 1),
                      ),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                    ),
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}

class _CountDownButton extends StatefulWidget {
  late int? delay;
  late String text;
  late Color? color;
  late bool border;
  late dynamic Function()? onPressed;

  _CountDownButton({
    Key? key,
    required this.text,
    this.color,
    this.delay,
    this.border: false,
    this.onPressed,
  }) : super(key: key);

  @override
  _CountDownButtonState createState() => new _CountDownButtonState();
}

class _CountDownButtonState extends State<_CountDownButton> {
  late Timer? timer = null;
  late int delay = widget.delay ?? 0;
  late String text = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (delay > 0) {
      text = '(${delay.toString()}s)';
      delay -= 1;
      timer = new Timer.periodic(Duration(seconds: 1), (timer) {
        if (delay > 0) {
          setState(() {
            text = '(${delay.toString()}s)';
            delay -= 1;
          });
        } else {
          timer.cancel();
          setState(() {
            text = widget.text;
          });
        }
      });
    } else {
      text = widget.text;
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Flexible(
      child: Container(
        decoration: widget.border
            ? BoxDecoration(
                border: Border(
                  right: BorderSide(color: Color(0xFFEEEEEE), width: 1),
                ),
              )
            : null,
        height: 43.w,
        child: TapTransitionWidget(
          onPressed: delay == 0 ? widget.onPressed : null,
          child: Center(
            child: Text(
              text,
              style: TextStyle(fontSize: 16.sp, color: widget.color),
            ),
          ),
        ),
      ),
    );
  }
}
